/**
 * main.js
 * @authors Your Name (you@example.org)
 * @date    2019-03-06 17:30:33
 * @version $Id$
 */

const Koa = require('koa');
var path=require('path'),
	static=require('koa-static'), //静态资源
	koaBody = require('koa-body');//接收参数
  router  = require('koa-router')(); //路由

const cors = require('koa2-cors'); //跨域

const adminRouters=require('./routers/index.js')
const appRoutrers=require('./routers/app.js')
const render = require('koa-art-template'); //渲染模板
const session = require('koa-session'); //session
const app = new Koa();

const {checkDirExist,getUploadDirName ,getFileName,getUploadFileExt}=require('./moduel/upload.config') //引用上传文件config


// 配置
app.use(static(__dirname+'/static')); //静态文件 css/js/less
app.use(static(__dirname+'/upload')); //文件上传目录

// session 设置 session 过期，用户登录过期
app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa:sess', 
  maxAge: 1000*60*30, //1000*60*60*24
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) 签名*/
  rolling: false, /** (boolean) 每次都重置设置*/
  renew: false, /** (boolean) 每次快要到期时重置设置*/
};
app.use(session(CONFIG, app));

// 跨域 
app.use(cors({
  origin: function (ctx) {
    console.log(ctx.url)
    let _url =ctx.url.split('/')[1]
    if(_url==='app'){
      return "*"; // 允许来自所有域名请求
    }
    // return 'http://localhost:3000'; // 这样就能只允许 http://localhost:3000 这个域名的请求了
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))


// 上传文件
app.use(koaBody({
  multipart:true, // 支持文件上传
  encoding:'utf-8',//gzip
  formidable:{
    uploadDir:path.join(__dirname,`upload`), // 设置文件上传目录
    keepExtensions: true,    // 保持文件的后缀
    maxFieldsSize:2 * 1024 * 1024, // 文件上传大小
    onFileBegin: (name,file) => { // 文件上传前的设置
      const dirName = getUploadDirName();
      const dir = path.join(__dirname, `upload/${dirName}`);
      // 判断目录是否存在，如不存在则创建该目录
      checkDirExist(dir);
      const ext =getUploadFileExt(file.name)
      let fileName= file.name!=""?getFileName(ext):'upload'
      file.path = `${dir}/${fileName}`;
      app.context.uploadpath = app.context.uploadpath ? app.context.uploadpath : {};
      app.context.uploadpath[name] = `${dirName}/${fileName}`;
    },
  }
}));


app.use(router.routes())
  .use(router.allowedMethods());
// 配置 koa-art-template
render(app, {
  root: path.join(__dirname, 'views'),
  // extname: '.art',
   extname: '.html',
  debug: process.env.NODE_ENV !== 'production'
});



// 404 处理
app.use(async (ctx,next)=>{
	await next();
	if(ctx.status==404){
		ctx.status=404;
		ctx.body='404  页面不存在'
	}
})



// 初起路由
router.use(adminRouters)
// 子级路由
router.use('/app',appRoutrers)



// 指定Ip
app.listen(3005,'192.168.61.87');
// 指定域名 
// app.listen(3000,'www.testWeb.com');  //192.168.61.208 www.testWeb.com  #hosts 配置

// app.listen(3000）  //单端口号